#ifndef _COMMON_UTIL_H_
#define _COMMON_UTIL_H_

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string>
#include "type.h"
#include <json/json.h>
#include <map>
#include <iostream>
#include <cstring>


using namespace std;

#define CONN_READ_TIMEOUT   (300)
#define CONN_WRITE_TIMEOUT (300)

typedef void (*sighandler_t)(int);
typedef void (*eventfunc)(int, short, void *);

void SafeClose(int fd);
void signal_handler(int sig, sighandler_t handler);
void run_daemon();

void PrintHexArray(const uint8* pArray, uint16 iLen);
void PrintASCIIArray(const uint8* pArray, uint16 iLen);
char hb2hex(unsigned char hb);
unsigned char hex2hb(unsigned char hb);
bool readJsonCfg(const char* filename, char* content);
bool readJsonCfg(const char* filename, Json::Value* pRoot);
bool writeJsonCfg(const char* filename,const char* content, int len);
int tcp_accept(int fd);
int tcp_listen(unsigned short port);
string GetEtherName();
int split(const char* src, char splitchar, char out[][8]);
void SplitString(string src, vector<string>& out, string c);

// 启动进程
void StartDaemonProcess(string process_name);
int KillProcess(string process_name);
string exec(const char* cmd) ;

template<class S, class T>
void ClearPointerMap(map<S, T*>& m)
{
    for(auto& item: m)
    {
        if(item.second != nullptr)
        {
            delete item.second;
            item.second = nullptr;
        }
    }
    m.clear();
}

template<class T>
void ClearPointerVector(vector<T*>& v)
{
    for(auto& item: v)
    {
        if(item != nullptr)
        {
            delete item;
            item = nullptr;
        }
    }
    v.clear();
}

bool isProcessRunning(const char* processName);

inline string to_string(const string& str)
{
    return str;
}

template<class T>
string generateSimpleId(T t)
{
    return to_string(t);
}


template<class T, typename ... Args>
string generateSimpleId(T t, Args... args)
{
    return to_string(t) + '_' + generateSimpleId(args...);
}


#endif /* _COMMON_UTIL_H_ */
